// 地址管理功能

// 显示添加地址表单
function showAddressForm() {
    const overlay = document.getElementById('addressFormOverlay');
    const formTitle = document.getElementById('formTitle');
    
    // 清空表单
    clearForm();
    formTitle.textContent = '添加地址';
    
    overlay.classList.add('show');
}

// 隐藏地址表单
function hideAddressForm() {
    const overlay = document.getElementById('addressFormOverlay');
    overlay.classList.remove('show');
}

// 清空表单
function clearForm() {
    document.getElementById('contactName').value = '';
    document.getElementById('contactPhone').value = '';
    document.getElementById('addressRegion').value = '天津市津南区';
    document.getElementById('addressDetail').value = '';
    document.getElementById('setAsDefault').checked = false;
}

// 编辑地址
function editAddress(addressId) {
    const overlay = document.getElementById('addressFormOverlay');
    const formTitle = document.getElementById('formTitle');
    
    formTitle.textContent = '编辑地址';
    
    // 根据addressId填充表单数据
    switch(addressId) {
        case 1:
            document.getElementById('contactName').value = '张三';
            document.getElementById('contactPhone').value = '13812345678';
            document.getElementById('addressRegion').value = '天津市津南区';
            document.getElementById('addressDetail').value = '海河教育园区雅观路135号天津大学北洋园校区47教第6机房';
            document.getElementById('setAsDefault').checked = true;
            break;
        case 2:
            document.getElementById('contactName').value = '李四';
            document.getElementById('contactPhone').value = '15912348888';
            document.getElementById('addressRegion').value = '天津市津南区';
            document.getElementById('addressDetail').value = '海河教育园区雅观路135号天津大学北洋园校区学生宿舍1号楼';
            document.getElementById('setAsDefault').checked = false;
            break;
        case 3:
            document.getElementById('contactName').value = '王五';
            document.getElementById('contactPhone').value = '18612346666';
            document.getElementById('addressRegion').value = '天津市津南区';
            document.getElementById('addressDetail').value = '海河教育园区雅观路135号天津大学北洋园校区教师公寓';
            document.getElementById('setAsDefault').checked = false;
            break;
    }
    
    overlay.classList.add('show');
}

// 删除地址
function deleteAddress(addressId) {
    if (confirm('确定要删除这个地址吗？')) {
        // 找到对应的地址项并删除
        const addressItems = document.querySelectorAll('.address-item');
        if (addressItems[addressId - 1]) {
            addressItems[addressId - 1].remove();
            showToast('地址删除成功');
        }
    }
}

// 设为默认地址
function setDefault(addressId) {
    // 移除所有默认标记
    const allItems = document.querySelectorAll('.address-item');
    allItems.forEach(item => {
        item.classList.remove('default');
        // 移除默认标签
        const defaultTag = item.querySelector('.default-tag');
        if (defaultTag) {
            defaultTag.remove();
        }
        // 显示设为默认按钮
        const defaultBtn = item.querySelector('.default-btn');
        if (defaultBtn) {
            defaultBtn.style.display = 'block';
        }
    });
    
    // 设置新的默认地址
    const targetItem = allItems[addressId - 1];
    if (targetItem) {
        targetItem.classList.add('default');
        
        // 添加默认标签
        const addressHeader = targetItem.querySelector('.address-header');
        const defaultTag = document.createElement('span');
        defaultTag.className = 'default-tag';
        defaultTag.textContent = '默认';
        addressHeader.appendChild(defaultTag);
        
        // 隐藏设为默认按钮
        const defaultBtn = targetItem.querySelector('.default-btn');
        if (defaultBtn) {
            defaultBtn.style.display = 'none';
        }
        
        showToast('已设为默认地址');
    }
}

// 保存地址
function saveAddress() {
    const name = document.getElementById('contactName').value.trim();
    const phone = document.getElementById('contactPhone').value.trim();
    const region = document.getElementById('addressRegion').value.trim();
    const detail = document.getElementById('addressDetail').value.trim();
    const isDefault = document.getElementById('setAsDefault').checked;
    
    // 验证表单
    if (!name) {
        showToast('请输入联系人姓名');
        return;
    }
    
    if (!phone) {
        showToast('请输入手机号');
        return;
    }
    
    if (!validatePhone(phone)) {
        showToast('请输入正确的手机号');
        return;
    }
    
    if (!detail) {
        showToast('请输入详细地址');
        return;
    }
    
    // 创建新地址项
    const newAddressItem = createAddressItem(name, phone, region + detail, isDefault);
    
    // 添加到地址列表
    const addressList = document.querySelector('.address-list');
    if (isDefault) {
        // 如果设为默认，先移除其他默认标记
        removeAllDefaultTags();
        addressList.insertBefore(newAddressItem, addressList.firstChild);
    } else {
        addressList.appendChild(newAddressItem);
    }
    
    // 隐藏表单
    hideAddressForm();
    showToast('地址保存成功');
}

// 创建地址项元素
function createAddressItem(name, phone, fullAddress, isDefault) {
    const div = document.createElement('div');
    div.className = 'address-item' + (isDefault ? ' default' : '');
    
    const maskedPhone = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    
    div.innerHTML = `
        <div class="address-info">
            <div class="address-header">
                <span class="name">${name}</span>
                <span class="phone">${maskedPhone}</span>
                ${isDefault ? '<span class="default-tag">默认</span>' : ''}
            </div>
            <div class="address-detail">
                ${fullAddress}
            </div>
        </div>
        <div class="address-actions">
            ${!isDefault ? '<button class="default-btn" onclick="setDefault(this)">设为默认</button>' : ''}
            <button class="edit-btn" onclick="editAddress(this)">
                <i class="fa fa-edit"></i>
            </button>
            <button class="delete-btn" onclick="deleteAddress(this)">
                <i class="fa fa-trash"></i>
            </button>
        </div>
    `;
    
    return div;
}

// 移除所有默认标记
function removeAllDefaultTags() {
    const allItems = document.querySelectorAll('.address-item');
    allItems.forEach(item => {
        item.classList.remove('default');
        const defaultTag = item.querySelector('.default-tag');
        if (defaultTag) {
            defaultTag.remove();
        }
        // 显示设为默认按钮
        const actions = item.querySelector('.address-actions');
        if (!actions.querySelector('.default-btn')) {
            const defaultBtn = document.createElement('button');
            defaultBtn.className = 'default-btn';
            defaultBtn.textContent = '设为默认';
            defaultBtn.onclick = () => setDefault(item);
            actions.insertBefore(defaultBtn, actions.firstChild);
        }
    });
}

// 验证手机号
function validatePhone(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
}

// 显示提示消息
function showToast(message) {
    // 创建toast元素
    const toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 10px 20px;
        border-radius: 5px;
        z-index: 9999;
        font-size: 14px;
    `;
    toast.textContent = message;
    
    document.body.appendChild(toast);
    
    // 2秒后移除
    setTimeout(() => {
        document.body.removeChild(toast);
    }, 2000);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 设置默认地区
    document.getElementById('addressRegion').value = '天津市津南区';
    
    // 点击地区选择框的处理（这里简化处理）
    document.getElementById('addressRegion').addEventListener('click', function() {
        showToast('地区选择功能开发中...');
    });
    
    // 点击遮罩层关闭弹窗
    document.getElementById('addressFormOverlay').addEventListener('click', function(e) {
        if (e.target === this) {
            hideAddressForm();
        }
    });
}); 